package application;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javafx.application.Platform;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.TilePane;

public class CheckNet implements Runnable {
	boolean connected;
	MainController mainCtrl;
	ToggleButton flesh;
	TilePane tp;
	FlowPane fp;
	public CheckNet(TilePane tp,FlowPane fp,ToggleButton flesh) {
		this.tp=tp;
		this.fp=fp;
		this.flesh=flesh;
	}
	public void run() {
		connected=false;
		URL url = null;
		try {
			url = new URL("http://baidu.com");
		} catch (MalformedURLException e) {e.printStackTrace();}
		
		while(!connected) {
			try {
				InputStream in = url.openStream();
				in.close();
				connected=true;
				break;
			} catch (IOException e) {connected=false;}
			break;
		}
		
		if(connected) {  //有网络连接时
			mainCtrl.s.startCrew();
			Animation.ispress=true;
		}
		else {
			Animation.ispress=false;
			tp.setVisible(false);
			Platform.runLater(new Runnable() {   //等待JavaFX线程来执行
        		@Override
        		public void run() {
        			fp.getChildren().clear();
        			if(flesh.isSelected()) mainCtrl.showConnectFail();
        			flesh.setSelected(false);
        			flesh.setText("开启");
        		}
        	});
		}
	}
	
	void setMainCtrl(MainController mainCtrl) {
		this.mainCtrl=mainCtrl;
	}
}
